﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Threading;
using LaberMediaClient.Dal;

namespace LaberMediaClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private DispatcherTimer timer;
        private DispatcherTimer timer2;
        double mediaLongth;

        string mediaFileName;
        string labelFileName;
        
        List<MyRect> rectangles = new List<MyRect>();
        int isTest = 1;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            mediaElement.LoadedBehavior = MediaState.Manual;
            mediaElement.UnloadedBehavior = MediaState.Manual;
            mediaElement.Volume = 0.5;
            mediaElement.MouseLeftButtonDown += MediaElement_MouseLeftButtonDown;
            //mediaElement.MediaEnded += (sender, e) => myMediaElement.Position = TimeSpan.Zero;
            //mediaElement.me
            this.Title = "LaberMedia";
            if (isTest == 1)
            {
                mediaFileName = @"D:\2topic\创作\汉字经过AI绘画之后全变成了小姐姐！.mp4";
                if(File.Exists(mediaFileName))
                    LoadMedia();
            }
            

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
            timer.Start();

            canvas.MouseDown += Canvas_MouseDown;
            canvas.MouseMove += Canvas_MouseMove;
            canvas.MouseUp += Canvas_MouseUp;

       

            ColorSelector.Init(comboColor);
            timer2 = new DispatcherTimer();
            timer2.Interval = TimeSpan.FromSeconds(0.03);
            timer2.Tick += (s,e) => { 
                timer2.Stop();
                mediaElement.Pause();
            };
        }

        private Point startPoint;
        private bool isDrawing;


       
        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(canvas);

            CreateRectDraw(startPoint, 1, 1);


            isDrawing = true;
        }

        void CreateRectDraw(Point startPoint,int w,int h)
        {
            // 创建一个矩形
            Rectangle rectangle = new Rectangle
            {
                Width =w,
                Height = h,
                //Fill = Brushes.Blue,
                Stroke = ColorSelector.GetLabelColor(comboColor),
                StrokeThickness = 2
            };

            // 设置矩形在 Canvas 中的位置
            Canvas.SetLeft(rectangle, startPoint.X);
            Canvas.SetTop(rectangle, startPoint.Y);

            // 将矩形添加到 Canvas 中
            canvas.Children.Add(rectangle);
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDrawing)
            {
                Point currentPoint = e.GetPosition(canvas);
                //PathGeometry pathGeometry = new PathGeometry();
                ////PathFigure pathFigure = new PathFigure();
                ////pathFigure.StartPoint = startPoint;
                ////pathFigure.Segments.Add(new LineSegment(currentPoint, true));
                ////pathGeometry.Figures.Add(pathFigure);


                //pathGeometry.Figures.Add(pathFigure);
                //path.Data = pathGeometry;

                var rectangle = canvas.Children[canvas.Children.Count-1] as Rectangle;
                var w= currentPoint.X - startPoint.X;
                var h= currentPoint.Y - startPoint.Y;
                //if (w > 0)
                    rectangle.Width =Math.Abs( w);
                //if (h > 0)
                    rectangle.Height = Math.Abs(h);
                //rectangle.VisualOffset= new Point(0,0);
                Canvas.SetLeft(rectangle, Math.Min(startPoint.X, currentPoint.X));
                Canvas.SetTop(rectangle, Math.Min(startPoint.Y, currentPoint.Y));
            }
        }

        private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isDrawing = false;
            Point currentPoint = e.GetPosition(canvas);
            if (Math.Abs(startPoint.X - currentPoint.X) < 5 && Math.Abs(startPoint.Y - currentPoint.Y) < 5)
                return;
            var rect = GetPercentRect(startPoint, currentPoint);
            rectangles.Add(rect);
        }

        MyRect GetPercentRect(Point start1,Point end1)
        {
            Point start = new Point(Math.Min(start1.X, end1.X), Math.Min(start1.Y, end1.Y));
            Point end= new Point(Math.Max(start1.X, end1.X), Math.Max(start1.Y, end1.Y));
            double x,y,w,h = 0;
            //var pictureSize=mediaElement.cur
            if (mediaElement.ActualHeight == canvas.ActualHeight)  //图片较窄
            {
                y=start.Y/mediaElement.ActualHeight;
                h=(end.Y-start.Y)/ mediaElement.ActualHeight;
                x=(start.X-(canvas.ActualWidth-mediaElement.ActualWidth)/2) / mediaElement.ActualWidth;
                w= (end.X - start.X) / mediaElement.ActualWidth;
            }
            else   //图片较宽
            {
                y = (start.Y - (canvas.ActualHeight - mediaElement.ActualHeight) / 2) / mediaElement.ActualHeight;
                h = (end.Y - start.Y) / mediaElement.ActualHeight;
                x = start.X  / mediaElement.ActualWidth;
                w = (end.X - start.X) / mediaElement.ActualWidth;
            }
            if(x<0) { x=0; }
            if(y<0) { y=0; }
            return new MyRect() {X=x,Y=y,W=w,H=h };
        }

        MyRect GetCanvasRect(MyRect percent)
        {
            double x, y, w, h = 0;
            //var pictureSize=mediaElement.cur
            if (mediaElement.ActualHeight == canvas.ActualHeight)  //图片较窄
            {
                y = percent.Y * mediaElement.ActualHeight;
                h = percent.H* mediaElement.ActualHeight;
                x =   percent.X * mediaElement.ActualWidth+ (canvas.ActualWidth - mediaElement.ActualWidth) / 2;
                w = percent.W* mediaElement.ActualWidth;
            }
            else   //图片较宽
            {
                y = percent.Y * mediaElement.ActualHeight + (canvas.ActualHeight - mediaElement.ActualHeight) / 2; 
                h = percent.H * mediaElement.ActualHeight;
                x = percent.X * mediaElement.ActualWidth;
                w = percent.W * mediaElement.ActualWidth;
            }
            return new MyRect() { X = x, Y = y, W = w, H = h };
        }

        bool isPlaying = true;
        private void MediaElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (mediaElement.Source != null )
            {
                if(isPlaying)
                    mediaElement.Pause();
                else
                    mediaElement.Play();
                isPlaying =!isPlaying;
            }
    
        }

        bool isCodeContralProgress=false;
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (isHandingProgress)
                return;
            if (mediaElement.Source != null&& mediaElement.NaturalDuration.HasTimeSpan)
            {
                isCodeContralProgress = true;
                progressSlider.Value = mediaElement.Position.TotalSeconds;
                isCodeContralProgress = false;
                //labelTime.Content = string.Format("{0}:{1} / {2}:{3}",
                //    Math.Floor(mediaElement.Position.TotalMinutes),
                //    mediaElement.Position.Seconds,
                //    Math.Floor(mediaElement.NaturalDuration.TimeSpan.TotalMinutes),
                //    mediaElement.NaturalDuration.TimeSpan.Seconds
                //    );

                //labelTime.Content = string.Format("{0} / {1}",
                //    mediaElement.Position.ToString(@"mm\:ss"),
                //    mediaElement.NaturalDuration.TimeSpan.ToString(@"mm\:ss")
                //    );
            }
        }
        private void buttonOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = openFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                mediaFileName = filePath;
                LoadMedia();

            }
        }

        private void LoadMedia()
        {
            var idx = mediaFileName.LastIndexOf(".");
            if (idx == -1)
                labelFileName = null;
            else
            {
                labelFileName = mediaFileName.Substring(0, idx) + ".txt";
                LabelManage.ClearLabels(comboLebal);
                LoadRecord();
            }
            mediaElement.Source = new Uri(mediaFileName);
            this.Title = "LaberMedia-" + new FileInfo(mediaFileName).Name;
            mediaElement.Play();
        }

        private void LoadRecord()
        {
            if (File.Exists(labelFileName))
            {
                var str = File.ReadAllText(labelFileName);
                listLabelRecord = JsonHelper.ParseJson<List<LabelModel>>(str);
                dataGrid.ItemsSource = listLabelRecord;
                foreach (var item in listLabelRecord)
                {
                    LabelManage.AddALabel(comboLebal, item.Label);
                }
                //textFileContent.Text = str;
            }
            else
            {
                listLabelRecord = new List<LabelModel>();
                dataGrid.ItemsSource = listLabelRecord;
                //textFileContent.Text = "";
            }
        }

        //c#winform视频播放-一种思路_c# mediaelement 换电脑无法播放视频-CSDN博客  https://blog.csdn.net/wqq1027/article/details/89894072
        //     MymediaElement.UnloadedBehavior = MediaState.Close;
        //MymediaElement.Close();
        //GC.Collect();

        //WPF中设置TEXTBOX为多行文本输入框_wpf 多行文本框-CSDN博客 https://blog.csdn.net/banmuhuangci/article/details/5619420





        private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            // 媒体文件打开时执行的操作
            progressSlider.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            
            //this.Title = "LaberMedia-"+ new FileInfo(mediaElement.Source.AbsoluteUri).Name;
        }

        private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            // 媒体文件播放结束时执行的操作
        }

        private void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            // 媒体文件播放失败时执行的操作
        }

        private void buttonPlay_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Play();
            }
        }

        private void buttonPause_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Pause();
            }
        }

        private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Stop();
            }
        }

        private void progressSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if(isHandingProgress)
                mediaElement.Position = TimeSpan.FromSeconds(progressSlider.Value);
            if(!isCodeContralProgress)
                mediaElement.Position = TimeSpan.FromSeconds(progressSlider.Value);
            var time1=TimeSpan.FromSeconds(progressSlider.Value);
            labelTime.Content = string.Format("{0}:{1} / {2}:{3}",
             Math.Floor(time1.TotalMinutes),
             time1.Seconds,
             Math.Floor(mediaElement.NaturalDuration.TimeSpan.TotalMinutes),
             mediaElement.NaturalDuration.TimeSpan.Seconds
             );
        }

        private void buttonPre_Click(object sender, RoutedEventArgs e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(mediaElement.Position.TotalSeconds-5);
        }

        private void buttonNext_Click(object sender, RoutedEventArgs e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(mediaElement.Position.TotalSeconds + 5);
        }

        List<LabelModel> listLabelRecord = new List<LabelModel>();
        private void buttonLabel_Click(object sender, RoutedEventArgs e)
        {
            listLabelRecord.Add(new LabelModel() { Time=mediaElement.Position,Label=comboLebal.Text,Rects=rectangles.ToList()});
            //textFileContent.Text = getLabelRecord();
            listLabelRecord=listLabelRecord.OrderBy(p => p.Time).ToList();
            dataGrid.ItemsSource = listLabelRecord;
            LabelManage.AddCurrentLabel( comboLebal);


        }
        string getLabelRecord()
        {
            string res = "";
            foreach(var i in listLabelRecord.OrderBy(p => p.Time))
            {
                res += string.Format("[{0}]{1}\n",
                    i.Time.ToString(@"mm\:ss"),
                    i.Label);

            }
            return res;
        }

        private void buttonOpenLabel_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = openFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                labelFileName = filePath;
                //if (File.Exists(labelFileName))
                //{
                //    var str = File.ReadAllText(labelFileName);
                //    listLabelRecord = JsonHelper.ParseJson<List<LabelModel>>(str);
                //    dataGrid.ItemsSource = listLabelRecord;
                //}
                LoadRecord();
            }
        }

        private void buttonSaveLabel_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty( labelFileName))
                return;
            var str = JsonHelper.Serialize(listLabelRecord);
            File.WriteAllText(labelFileName, str);
            MessageBox.Show("保存成功");
        }

        private void buttonSaveAs_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = labelFileName;
            if (saveFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string filePath = saveFileDialog.FileName;
                // 这里可以进行文件路径的进一步处理
                labelFileName = filePath;
                buttonSaveLabel_Click(null, null);

            }
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           var idx= dataGrid.SelectedIndex;
            if (idx == -1)
                return;
            var item = listLabelRecord[idx];
            mediaElement.Position = item.Time;
            MediaRefreshPicture();
           
            comboLebal.Text = item.Label;
            if (item.Rects == null)
                item.Rects = new List<MyRect>();
            rectangles=item.Rects.ToList();
            canvas.Children.Clear();
            foreach(var percent in rectangles)
            {
                var rect=GetCanvasRect(percent);
                var startPoint=new Point((int)rect.X, (int)rect.Y);
                CreateRectDraw(startPoint, (int)rect.W, (int)rect.H);
            }
        }
        /// <summary>
        /// 修改视频时间时，使画面更新
        /// </summary>
        void MediaRefreshPicture()
        {
            //没有效果
            //mediaElement.ScrubToPosition(mediaElement.Position);
            //mediaElement.InvalidateVisual();
            //mediaElement.UpdateLayout();

            mediaElement.Play();
            timer2.Start();
        }

        private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {

        }

        private void buttonLabelDel_Click(object sender, RoutedEventArgs e)
        {
            var toDel = new List<LabelModel>();
            foreach (var i in dataGrid.SelectedCells)
            {
                var model = i.Item as LabelModel;
                if (!toDel.Contains(model))
                    toDel.Add(model);
            }
            foreach (var i in toDel)
            {
                listLabelRecord.Remove(i);
            }
            dataGrid.ItemsSource = listLabelRecord.ToList();
        }

        private void buttonRectDel_Click(object sender, RoutedEventArgs e)
        {
            canvas.Children.Clear();
            rectangles.Clear();
        }
        /// <summary>
        /// 没有生效
        /// </summary>
        bool isHandingProgress = false;
        /// <summary>
        /// 没有触发 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void progressSlider_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isHandingProgress= true;
            timer.Stop();
        }

        private void progressSlider_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isHandingProgress = false;
          
            //MediaRefreshPicture();
            timer.Start();
        }
    }


}
